<template>
    <div>
        <el-container>
            <el-main>
                <el-row :gutter="20">
                    <el-col v-for="item in productList" :key="item.id" :span="6">
                        <el-card :body-style="{ padding: '0px' }">
                            <img :src="item.image" class="product-image" />
                            <div style="padding: 14px;">
                                <span>{{ item.name }}</span>
                                <div class="bottom">
                                    <span>价格: {{ item.price }}元</span>
                                    <el-button type="text" class="button" @click="addToCart(item)">
                                        加入购物车
                                    </el-button>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </el-main>
        </el-container>
    </div>
</template>

<script>
export default {
    name: 'FrontGoodsAll',
    data() {
        return {
            productList: [], // 商品列表
        };
    },
    created() {
        this.fetchProducts(); // 页面创建时获取商品数据
    },
    watch: {
        // 监听路由参数变化
        '$route.query.categoryId': {
            handler: 'fetchProducts',
            immediate: true,
        },
    },
    methods: {
        // 获取商品数据
        async fetchProducts() {
            const categoryId = this.$route.query.categoryId;
            if (!categoryId) return;

            try {
                const response = await this.$axios.get(`product/getByCategory?categoryId=${categoryId}`);
                this.productList = response.data;
                console.log('商品数据:', this.productList);
            } catch (error) {
                console.error('获取商品数据失败:', error);
            }
        },
        // 加入购物车
        addToCart(product) {
            const cart = JSON.parse(localStorage.getItem('cart')) || [];
            const existingProduct = cart.find((item) => item.id === product.id);

            if (existingProduct) {
                existingProduct.quantity += 1; // 如果商品已存在，增加数量
            } else {
                cart.push({ ...product, quantity: 1 }); // 如果商品不存在，添加到购物车
            }

            localStorage.setItem('cart', JSON.stringify(cart));
            this.$message.success('已加入购物车');
        },
    },
};
</script>

<style scoped>
.product-image {
    width: 100%;
    height: 200px;
    object-fit: cover;
}

.bottom {
    margin-top: 10px;
    line-height: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.button {
    padding: 0;
    min-height: auto;
}
</style>